'use client';

import { useState } from 'react';
import { RefreshCw, ExternalLink, Filter } from 'lucide-react';

interface Trade {
  id: string;
  type: 'BUY' | 'SELL';
  amount: number;
  price: number;
  totalValue: number;
  txHash?: string;
  status: 'PENDING' | 'COMPLETED' | 'FAILED' | 'CANCELLED';
  positionIndex: number;
  createdAt: string;
  token: {
    id: string;
    symbol: string;
    name: string;
    chain: string;
  };
}

interface TradeHistoryProps {
  trades: Trade[];
  onRefresh: () => void;
}

export default function TradeHistory({ trades, onRefresh }: TradeHistoryProps) {
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [filter, setFilter] = useState({
    type: 'ALL',
    status: 'ALL',
    chain: 'ALL'
  });

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await onRefresh();
    setIsRefreshing(false);
  };

  const formatNumber = (num: number, decimals: number = 2) => {
    if (Math.abs(num) >= 1e9) return (num / 1e9).toFixed(decimals) + 'B';
    if (Math.abs(num) >= 1e6) return (num / 1e6).toFixed(decimals) + 'M';
    if (Math.abs(num) >= 1e3) return (num / 1e3).toFixed(decimals) + 'K';
    return num.toFixed(decimals);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'COMPLETED':
        return 'status-active';
      case 'PENDING':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case 'FAILED':
        return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
      case 'CANCELLED':
        return 'status-inactive';
      default:
        return 'status-inactive';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'COMPLETED':
        return '已完成';
      case 'PENDING':
        return '进行中';
      case 'FAILED':
        return '失败';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  };

  const getChainColor = (chain: string) => {
    switch (chain) {
      case 'SOLANA':
        return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200';
      case 'BSC':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case 'BASE':
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
    }
  };

  const getExplorerUrl = (chain: string, txHash: string) => {
    switch (chain) {
      case 'SOLANA':
        return `https://solscan.io/tx/${txHash}`;
      case 'BSC':
        return `https://bscscan.com/tx/${txHash}`;
      case 'BASE':
        return `https://basescan.org/tx/${txHash}`;
      default:
        return '#';
    }
  };

  // 过滤交易记录
  const filteredTrades = trades.filter(trade => {
    if (filter.type !== 'ALL' && trade.type !== filter.type) return false;
    if (filter.status !== 'ALL' && trade.status !== filter.status) return false;
    if (filter.chain !== 'ALL' && trade.token.chain !== filter.chain) return false;
    return true;
  });

  // 统计数据
  const stats = {
    totalTrades: filteredTrades.length,
    completedTrades: filteredTrades.filter(t => t.status === 'COMPLETED').length,
    totalVolume: filteredTrades
      .filter(t => t.status === 'COMPLETED')
      .reduce((sum, t) => sum + t.totalValue, 0),
    buyTrades: filteredTrades.filter(t => t.type === 'BUY' && t.status === 'COMPLETED').length,
    sellTrades: filteredTrades.filter(t => t.type === 'SELL' && t.status === 'COMPLETED').length
  };

  return (
    <div className="space-y-6">
      {/* 头部操作栏 */}
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">
          交易历史
        </h2>
        <button
          onClick={handleRefresh}
          disabled={isRefreshing}
          className="btn-primary flex items-center space-x-2"
        >
          <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
          <span>刷新</span>
        </button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        <div className="card">
          <div className="text-sm text-gray-500 dark:text-gray-400">总交易数</div>
          <div className="text-2xl font-bold text-gray-900 dark:text-white">
            {stats.totalTrades}
          </div>
        </div>
        <div className="card">
          <div className="text-sm text-gray-500 dark:text-gray-400">已完成</div>
          <div className="text-2xl font-bold text-green-600">
            {stats.completedTrades}
          </div>
        </div>
        <div className="card">
          <div className="text-sm text-gray-500 dark:text-gray-400">总成交额</div>
          <div className="text-2xl font-bold text-gray-900 dark:text-white">
            ${formatNumber(stats.totalVolume)}
          </div>
        </div>
        <div className="card">
          <div className="text-sm text-gray-500 dark:text-gray-400">买入次数</div>
          <div className="text-2xl font-bold text-blue-600">
            {stats.buyTrades}
          </div>
        </div>
        <div className="card">
          <div className="text-sm text-gray-500 dark:text-gray-400">卖出次数</div>
          <div className="text-2xl font-bold text-orange-600">
            {stats.sellTrades}
          </div>
        </div>
      </div>

      {/* 过滤器 */}
      <div className="card">
        <div className="flex items-center space-x-4">
          <Filter className="w-5 h-5 text-gray-500" />
          <div className="flex space-x-4">
            <select
              value={filter.type}
              onChange={(e) => setFilter(prev => ({ ...prev, type: e.target.value }))}
              className="select w-32"
            >
              <option value="ALL">所有类型</option>
              <option value="BUY">买入</option>
              <option value="SELL">卖出</option>
            </select>
            <select
              value={filter.status}
              onChange={(e) => setFilter(prev => ({ ...prev, status: e.target.value }))}
              className="select w-32"
            >
              <option value="ALL">所有状态</option>
              <option value="COMPLETED">已完成</option>
              <option value="PENDING">进行中</option>
              <option value="FAILED">失败</option>
            </select>
            <select
              value={filter.chain}
              onChange={(e) => setFilter(prev => ({ ...prev, chain: e.target.value }))}
              className="select w-32"
            >
              <option value="ALL">所有链</option>
              <option value="SOLANA">Solana</option>
              <option value="BSC">BSC</option>
              <option value="BASE">Base</option>
            </select>
          </div>
        </div>
      </div>

      {/* 交易列表 */}
      <div className="card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="table">
            <thead>
              <tr>
                <th>时间</th>
                <th>代币</th>
                <th>链</th>
                <th>类型</th>
                <th>数量</th>
                <th>价格</th>
                <th>总价值</th>
                <th>状态</th>
                <th>交易哈希</th>
              </tr>
            </thead>
            <tbody>
              {filteredTrades.map((trade) => (
                <tr key={trade.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                  <td>
                    <div className="text-sm">
                      {new Date(trade.createdAt).toLocaleString('zh-CN')}
                    </div>
                  </td>
                  <td>
                    <div>
                      <div className="font-medium">{trade.token.symbol}</div>
                      <div className="text-sm text-gray-500 dark:text-gray-400">
                        {trade.token.name}
                      </div>
                    </div>
                  </td>
                  <td>
                    <span className={`status-indicator ${getChainColor(trade.token.chain)}`}>
                      {trade.token.chain}
                    </span>
                  </td>
                  <td>
                    <span className={`status-indicator ${
                      trade.type === 'BUY' 
                        ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                        : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                    }`}>
                      {trade.type === 'BUY' ? '买入' : '卖出'}
                    </span>
                  </td>
                  <td>
                    <div className="font-mono">
                      {formatNumber(trade.amount, 4)}
                    </div>
                  </td>
                  <td>
                    <div className="font-mono">
                      ${trade.price.toFixed(6)}
                    </div>
                  </td>
                  <td>
                    <div className="font-mono">
                      ${formatNumber(trade.totalValue)}
                    </div>
                  </td>
                  <td>
                    <span className={`status-indicator ${getStatusColor(trade.status)}`}>
                      {getStatusText(trade.status)}
                    </span>
                  </td>
                  <td>
                    {trade.txHash ? (
                      <a
                        href={getExplorerUrl(trade.token.chain, trade.txHash)}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="flex items-center space-x-1 text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
                      >
                        <span className="font-mono text-sm">
                          {trade.txHash.slice(0, 8)}...
                        </span>
                        <ExternalLink className="w-3 h-3" />
                      </a>
                    ) : (
                      <span className="text-gray-400">-</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filteredTrades.length === 0 && (
          <div className="text-center py-12">
            <p className="text-gray-500 dark:text-gray-400">
              {trades.length === 0 ? '暂无交易记录' : '没有符合条件的交易记录'}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
